package org.example.structure.proxy;

import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * 类描述：Jdk动态代理的深入学习
 * <br>
 *
 * @author ZS
 * @version 1.0
 * @date 2020/12/29
 **/
public class DynamicProxyDemo1 {
    interface Inter1 {
        void play();
    }

    interface Inter2 {
        String talk(int i, String str);
    }

    public static void main(String[] args) {
        // 当前线程的应用类加载器
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        // 接口数组
        Class<?>[] inters = new Class[]{Inter1.class, Inter2.class};

        // 动态创建一个实现了inter1接口和inter2接口的实例
        Object o = Proxy.newProxyInstance(loader, inters, (proxy, method, values) -> {
            String name = method.getName();
            System.out.println("当前执行的方法：" + name);
            System.out.println("传入的参数：" + Arrays.toString(values));
            System.out.println(method.getGenericReturnType().getTypeName());

            if ("java.lang.String".equalsIgnoreCase(method.getGenericReturnType().getTypeName())) {
                return "世界";
            }
            return null;
        });

        ((Inter1) o).play();
        String talk = ((Inter2) o).talk(12, "世界");
        System.out.println(talk);

        // 打印jdk动态代理生成的对象
        // org.example.structure.proxy.$Proxy0
        System.out.println(o.getClass().getName());
    }
}
